//
//  UIButton+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/11.
//

import UIKit

extension UIButton {
    // MARK: - 按钮边距构造方法
    convenience init(title : String, titleColor : UIColor, font : UIFont) {
        self.init()
        self.setTitle(title, for: .normal)
        self.setTitleColor(titleColor, for: .normal)
        self.titleLabel?.font = font
    }

    private struct AssociatedKey {
        static var identifier: String = "identifier"
    }
    var touchAreaInsets : UIEdgeInsets {
        get {
            objc_getAssociatedObject(self, &AssociatedKey.identifier) as? UIEdgeInsets ?? UIEdgeInsets.zero
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.identifier, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
    
    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let bounds : CGRect = CGRect(x: bounds.origin.x - touchAreaInsets.left, y: bounds.origin.y - touchAreaInsets.top, width: bounds.size.width + touchAreaInsets.left + touchAreaInsets.right, height: bounds.size.height + touchAreaInsets.bottom + touchAreaInsets.top)
        return bounds.contains(point)
    }
    
    // MARK: - 按钮倒计时方法 支持过程中自定义修改button样式
    func countdownButtonWith(timeout : Int, processBlock : @escaping(_ button : UIButton, _ time : Int) -> Void, completeBlock : @escaping(_ button : UIButton) -> Void) {
        var time = timeout
        let queue : DispatchQueue = .global()
        let source : DispatchSourceTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: queue)
        source.schedule(deadline: .now(), repeating: .milliseconds(1000))
        source.setEventHandler { [weak self] in
            if time <= 0 {
                source.cancel()
                DispatchQueue.main.async {
                    if self != nil {
                        completeBlock(self!)
                        self?.isUserInteractionEnabled = true
                    }
                }
            } else {
                DispatchQueue.main.async {
                    if self != nil {
                        processBlock(self!, time)
                        self?.isUserInteractionEnabled = false
                    }
                }
            }
            time -= 1
        }
        source.activate()
    }

    func setBackgroundWithColor(_ color : UIColor, for state: UIControl.State) {
        setBackgroundImage(.qmui_image(with: color), for: state)
    }

    //MARK: - UIButton加载图片便捷方法 可设置回调
    func setAFImageWith(_ url : String, _ size : CGSize, _ placeholderImage : UIImage? = nil, _ completedBlock: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) {
        if url.isEmpty {
            setImage(placeholderImage, for: .normal)
            return
        }
        var url : String = (url.removingPercentEncoding?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!

        if url.contains("aliyuncs") {
            if size != .zero {
                url = url + "?x-oss-process=image/resize,w_\(Int(size.width * 2)),h_\(Int(size.height * 2))"
            }
            kf.setImage(with: URL(string: url)!, for: .normal, placeholder: placeholderImage, options: [.transition(.fade(0.5))], progressBlock: nil, completionHandler: completedBlock)
        } else if size != .zero {
            let processor = DownsamplingImageProcessor(size: CGSize(width: size.width * 2, height: size.height * 2))
            kf.setImage(with: URL(string: url)!, for: .normal, placeholder: placeholderImage, options: [.processor(processor), .transition(.fade(0.5))], progressBlock: nil, completionHandler: completedBlock)
        } else {
            kf.setImage(with: URL(string: url)!, for: .normal, placeholder: placeholderImage, options: [.transition(.fade(0.5))], progressBlock: nil, completionHandler: completedBlock)
        }
    }
}
